package uk.gov.swmprobation.cpvisibility;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends MyActivity {

	public static final int SELECT_IMAGE = 0;
	private int type;
	private ListView list;
	private List<Project> projects;
	private LinearLayout optionView;
	private BroadcastReceiver backgroundUpdate;
	private Uri fileUri;
	private static ImageButton camera;
	private static ImageButton search;
	private static ImageView networkInfo;
	
	LocationServices ls = new LocationServices(this);
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initVariables();
        
        //Service to connect to message broker
        Intent MQTTIntent = new Intent(this,MQTTConnection.class);
		this.startService(MQTTIntent); 
        
        list.setOnItemClickListener(selectListItem);

        backgroundUpdate = new BroadcastReceiver(){

			@Override
			public void onReceive(Context contrext, Intent intent) {
				RefreshView();				
				abortBroadcast();
			}
        	
        };        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.application_menu, menu);
        return true;
    }
    
    public void onPause(){
    	super.onPause();
    	unregisterReceiver(backgroundUpdate);
    	LocationServices.stopListener();
    }
    
    public void onResume() {
    	super.onResume();
        RefreshView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("uk.gov.swmprobation.cpvisibility.event.sentprojects");
        intentFilter.setPriority(1);
        registerReceiver(backgroundUpdate, intentFilter);
        //Show Hint each time until setting changed
        if (sharedPref.getBoolean(SettingsActivity.mainHintTitle, true)){
			Helper.showHintDialog(this, SettingsActivity.mainHintTitle, SettingsActivity.mainHintMessage);
		}
        if (LocationServices.locationAvailable()){
        	enabledButtons(true);
        } else {
        	ls.GetLastLocation();
        	ls.GetALocation();
        	enabledButtons(false);
        }
    }
    
    private void initVariables(){
    	camera = (ImageButton) findViewById(R.id.camera_button);
        search = (ImageButton) findViewById(R.id.search_button);
        networkInfo = (ImageView) findViewById(R.id.network_info);
        type = 0;
        optionView = (LinearLayout) findViewById(R.id.tab_bar);
        list = (ListView) findViewById( R.id.list );
        TextView version = (TextView) findViewById(R.id.app_version);
        try {
			String versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0 ).versionName;
	        version.setText("Version: " + versionName);
		} catch (NameNotFoundException e) {
	        version.setText("Version data not found");
		}  
    }
    
    public void RefreshView(){
    	ShowOptions();
    	ListProjects();
    }
    
    private void ShowOptions(){
    	optionView.removeAllViews();
    	if(DatabaseHandler.getProjectsCount()>0){
    		if(DatabaseHandler.getProjectsCountType(type)==0) type = 0;
    		List<Integer> types = DatabaseHandler.getProjectTypes();
    		int n = types.size();
	    	for(int i = 0; i < n; i++) {
	    		int typeInt = types.get(i);
	    		View v = newOption(Project.TYPE_NAMES[typeInt], typeInt);
	    		optionView.addView(v);
	    		if (type==0) {
	    			type = typeInt;
	    		}
	    	}
    	} else {
    		View v = newOption("Projects", Project.TYPE_MINE);
    		optionView.addView(v);
    		type = Project.TYPE_MINE;
    	}
    	optionView.findViewWithTag(type).setBackgroundResource(R.drawable.button_as_tab_selected);
    }
    
    private OnClickListener selectList = new OnClickListener(){

		@Override
		public void onClick(View v) {
			int tag = (Integer) v.getTag();
			optionView.findViewWithTag(type).setBackgroundResource(R.drawable.button_as_tab);
			v.setBackgroundResource(R.drawable.button_as_tab_selected);
			type = tag;
			ListProjects();
		}
    	
    };
    
    private OnItemClickListener selectListItem = new OnItemClickListener(){
        public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        	Project projectToOpen = projects.get(position);
        	
        	Intent openProjectView;
        	if (projectToOpen.getProjectType()==Project.TYPE_DRAFT) {
        		openProjectView = new Intent(MainActivity.this, CreateProject.class);
        		int idToOpen = projectToOpen.getId();
        		openProjectView.putExtra("id", idToOpen);
        	} else {
        		openProjectView = new Intent(MainActivity.this, ProjectReview.class);
        		int projectIdToOpen = projectToOpen.getProjectId();
        		openProjectView.putExtra("project_id", projectIdToOpen);
        		openProjectView.putExtra("updated", projectToOpen.getUpdated());
        	}
      	    startActivity(openProjectView);
        }
    };
      
    private Button newOption(String buttonName, int type){
    	Button optionButton = new Button(this);
    	optionButton.setText(buttonName);
    	optionButton.setTag(type);
    	optionButton.setOnClickListener(selectList);
    	optionButton.setBackgroundResource(R.drawable.button_as_tab);
		return optionButton;
    	
    }

    public static void enabledButtons(boolean enabled){
    	if (enabled){
    		camera.setVisibility(View.VISIBLE);
    		search.setVisibility(View.VISIBLE);
    		networkInfo.setVisibility(View.GONE);
    		
    	} else {
    		camera.setVisibility(View.GONE);
    		search.setVisibility(View.GONE);
    		networkInfo.setVisibility(View.VISIBLE);
    	}
    }
    
    public void deleteProject(View v) 
    {
        //get the row the clicked button is in
        RelativeLayout parentRow = (RelativeLayout)v.getParent();
        
        TextView idText = (TextView) parentRow.getChildAt(0);
        
        int localId = Integer.parseInt((String) idText.getText());
        
        DatabaseHandler.deleteProject(localId);
        RefreshView();
    }
    
    public void takePhoto(View view) {
	    if(!LocationServices.locationAvailable()){
	    	Toast.makeText(this, "Looking for your location, please try again later", Toast.LENGTH_SHORT).show();
	    	return;
	    }
	    
	    if(System.currentTimeMillis()-LocationServices.getLocationTime()>LocationServices.FEW_MINUTES){
	    	Toast.makeText(this, "Location information may be out of date", Toast.LENGTH_SHORT).show();
	    }
	    
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
		fileUri = getOutputMediaFileUri();
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

	    startActivityForResult(takePictureIntent, SELECT_IMAGE);
        } else {
        	Toast.makeText(this, "Can't access SD Card", Toast.LENGTH_SHORT).show();
        }
    }
    
    public void searchProjects(View view) {
    	//Get GPS co-ordinates
	    if(!LocationServices.locationAvailable()){
	    	Toast.makeText(this, "Looking for your location, please try again later", Toast.LENGTH_SHORT).show();
	    	return;
	    }
	    if(System.currentTimeMillis()-LocationServices.getLocationTime()>LocationServices.FEW_MINUTES){
	    	Toast.makeText(this, "Location information may be out of date", Toast.LENGTH_SHORT).show();
	    }
	    double lat = LocationServices.getLocationLat();
	    double lng = LocationServices.getLocationLng();
		Intent searchNearby = new Intent(this,SearchProjects.class);
		searchNearby.putExtra("lat", lat);
		searchNearby.putExtra("lng", lng);
	    startActivity(searchNearby);
    }
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  super.onActivityResult(requestCode, resultCode, data);
	  if (requestCode == SELECT_IMAGE)
	    if (resultCode == Activity.RESULT_OK) {
	      Uri selectedImage = fileUri;
	    //Get GPS co-ordinates
	      double lat = LocationServices.getLocationLat();
		  double lng = LocationServices.getLocationLng();
	      Project newproject = new Project(selectedImage, lat, lng);
	      // Store project
	      newproject.save();
	      // TODO Test internet access

	      //If pass open next activity
	      Intent createProject = new Intent(this, CreateProject.class);
	      createProject.putExtra("id", newproject.getId());
	      startActivity(createProject);
	      
	    } 
	}
    
    private void ListProjects(){
    	/**
         * CRUD Operations
         * */
               
        list.setAdapter(new ProjectListAdapter(type));
    }

    /** Create a file Uri for saving an image */
    private static Uri getOutputMediaFileUri(){
          return Uri.fromFile(getOutputMediaFile());
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(){
    	File mediaFile;
        //Check SDCard is mounted
    	String state = Environment.getExternalStorageState();

    	if (state.equals(Environment.MEDIA_MOUNTED)) {
	        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	                  Environment.DIRECTORY_PICTURES), "SWM");
	
	        // Create the storage directory if it does not exist
	        if (! mediaStorageDir.exists()){
	            if (! mediaStorageDir.mkdirs()){
	                return null;
	            }
	        }
	
	        // Create a media file name
	        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
    	} else {
    		return null;
    	}
        return mediaFile;
    }
  
    private class ProjectListAdapter extends BaseAdapter{
    	
    	Boolean enable_delete=true;
    		
    	ProjectListAdapter(int type) {
    		projects = DatabaseHandler.getTypeProjects(type);
    		final Boolean enable_delete = (type != Project.TYPE_MINE);
    	}
    	
			@Override
			public int getCount() {
				return projects.size();
			}

			@Override
			public Object getItem(int pos) {
				return projects.get(pos);
			}

			@Override
			public long getItemId(int pos) {
				return pos;
			}

			@Override
			public View getView(int pos, View view, ViewGroup viewGroup) {
				view = View.inflate(MainActivity.this, R.layout.projectlist_item, null);
				
				Project project = (Project) getItem(pos);
				
				TextView text = (TextView) view.findViewById(R.id.local_id);
	            text.setText(String.valueOf(project.getId()));
				
	            String describeProject=Helper.shortName(project.getProjectName());
	            if (project.getUpdated()) describeProject =describeProject +" (Updated)";
	            
				text = (TextView) view.findViewById(R.id.project_name);
	            text.setText(describeProject);

	            text = (TextView) view.findViewById(R.id.project_status);
	            text.setText(project.getProjectStatus());
	            if (project.getProjectStatus().equals("Draft")) {
	            	text.setTextColor(getResources().getColor(R.color.Draft));
	            }
	            else if (project.getProjectStatus().equals("new")) {
	            	text.setTextColor(getResources().getColor(R.color.New));
	            }
	            else {
	            	text.setTextColor(getResources().getColor(R.color.Default));
	            }
	            
	            ImageButton button = (ImageButton) view.findViewById(R.id.delete_button);
				button.setFocusable(false);
				button.setEnabled(enable_delete);
	            
	            return view;
			}};
               
}
